// pages/pay/pay.js
import http from '../../api/api'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cartList: [],
        totalPrice: 0,
        address: {},
    },




    /**
     * 获取商品列表
     */
    getCartList() {
        const cart = wx.getStorageSync('cart') || [];
        const address = wx.getStorageSync('address') || {}
        let totalPrice = 0;
        const cartList = cart.filter(v => v.checked);
        cartList.forEach(v => totalPrice += v.num * v.goods_price);
        this.setData({
            cartList,
            totalPrice,
            address
        })
    },

    /**
     * 支付
     */
    async onClickButton() {
        try {
            const userInfo = wx.getStorageSync('userInfo')
            const token = wx.getStorageSync('token')
            if (!Object.keys(userInfo).length || !token) return wx.navigateTo({
                url: '/pages/info/info'
            })


            // 创建订单
            const {
                totalPrice,
                cartList,
                address
            } = this.data;

            if (!cartList.length) return wx.showToast({
                title: '支付列表为空',
                icon: 'none'
            })
            // 把cartList里面提取出来的商品信息，放到一个数组里面
            const goods = cartList.map(v => ({
                goods_id: v.goods_id,
                goods_number: v.num,
                goods_price: v.goods_price
            }));
            const obj = {
                order_price: totalPrice,
                consignee_addr: address.all,
                goods
            }
            const {
                message: {
                    order_number
                }
            } = await http.addOrders(obj)

            // 支付
            // await http.pay(order_number)


            // 查询支付状态
            const {
                meta: {
                    msg
                }
            } = await http.chkOrder(order_number)
            wx.showToast({
                title: msg
            })


            // 清除购物车
            const cart = wx.getStorageSync('cart').filter(v => !v.checked);
            wx.setStorageSync('cart', cart)


            wx.navigateTo({
                url: '/pages/order/order'
            })
        } catch (error) {

        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCartList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})